<?php

class Auth extends Core {
	public $error;
	protected $resources = array();
	
	public function __construct() {
		if ($this->is_logged()) {
			$this->resources = $this->identificators();
		}
	}

	public function logged() {
		return (isset($_SESSION['auth.username'])) ? $_SESSION['auth.username'] : '';
	}
	
	public function is_logged() {
		if (isset($_SESSION['auth.username'])) {
			$_SESSION['auth.time'] = time();
			return true;
		}
		return false;
	}

	public function identificators() {
		$identificator = array();
		$identificators = $this->Account->get_options($this->logged());
		foreach ($identificators as $key => $value) {
			$data[$key] = $value;
			$identificator[] = $data[$key]['identificator'];
		}
		return $identificator;
	}

	public function check($username = null, $password = null) {
		$rs = $this->Database->query('SELECT COUNT(1) AS total FROM MEMB_INFO WHERE memb___id = %s AND memb__pwd = %s', $username, $password)->fetch();
		return $rs['total'] == 1;
	}
	
	public function is_valid($resource) {
		return in_array($resource, $this->resources);
	}
	
	public function login($username, $password) {
		if ($this->is_logged()) $this->redirect('/');
		$username = trim(strip_tags($username));
		$password = trim(strip_tags($password));
		if (!$this->check($username, $password)) {
			$this->error = 'Usu&aacute;rio e/ou senha est&atilde;o incorretos.';
		} else {
			$_SESSION['auth.username'] = $username;
			$_SESSION['auth.time'] = time();
			return true;
		}
		return false;
	}
	
	public function logout() {
		unset($_SESSION['auth.username']);
		unset($_SESSION['auth.time']);
		session_destroy();
		$this->redirect('/');
	}
}

?>